<template>
  <Validator ref="refStep1" @submit="changeCurStep(2)" />
  <SealSelector
    purpose="gap"
    ref="refStep2"
    @submit="
      params => {
        onAddSeal(params);
      }
    "
  />
</template>
<script setup>
import { reactive, toRefs, ref, nextTick, inject } from "vue";
import _, { transform } from "lodash";
import Validator from "./_validator.vue";
import SealSelector from "./_sealSelector.vue";
import $ from "jquery";
import interact from "interactjs";
import { format, seal, ss } from "@/utils";
import { useResizeObserver, useDebounceFn } from "@vueuse/core";

const refStep1 = ref();
const refStep2 = ref();
const provideHome = inject("provideHome");
const { setBoxTemporarySeal } = provideHome.methods;

const state = reactive({
  style: {},
  sealInfo: {},
});
const { style } = toRefs(state);

let /** 悬浮印章显示宽度 */
  hoverSealShowWidth = 0,
  /** 悬浮印章显示高度 */
  hoverSealShowHeight = 0,
  /** 悬浮印章原始宽度 */
  hoverSealRawWidth = 0,
  /** 悬浮印章元素高度 */
  hoverSealRawHeight = 0,
  /** 添加印章所处状态 */
  statusSealAdd = "",
  /** 是否已绑过事件，用于控制只绑一次事件 */
  hasBindSealAddEvents = false;

const EnumStatusAddSeal = {
  /** confirm 确认印章 */
  confirm: "confirm",
  /** 不处于添加印章状态 */
  none: "",
};

const changeCurStep = curStep => {
  refStep1.value.close();
  refStep2.value.close();
  if (curStep == 1) {
    refStep1.value.show();
  } else if (curStep == 2) {
    refStep2.value.show();
  }
  setTimeout(() => {
    provideHome.methods.setSealCurrentOperateName("btnSealAddGap");
  }, 30);
};
const onAddSeal = infos => {
  state.sealInfo = infos.sealInfo;
  hoverSealRawWidth = state.sealInfo.width;
  hoverSealRawHeight = state.sealInfo.height;
  onReset();
  initDragArea();
};

const setSealSizeByScale = () => {
  if ([EnumStatusAddSeal.confirm].includes(statusSealAdd)) {
    var scaleFactor = seal.getScaleFactor();
    hoverSealShowWidth = hoverSealRawWidth * scaleFactor;
    hoverSealShowHeight = hoverSealRawHeight * scaleFactor;
  }
};

const bindSealAddEvents = () => {
  if (!hasBindSealAddEvents) {
    hasBindSealAddEvents = true;
    useResizeObserver(
      document.getElementById("viewer"),
      useDebounceFn(() => {
        if (
          provideHome.boxTemporarySeal &&
          statusSealAdd == EnumStatusAddSeal.confirm
        ) {
          setSealSizeByScale();
          let { style } = provideHome.boxTemporarySeal;
          style.setProperty("--sealWidth", hoverSealShowWidth + "px");
          style.setProperty("--sealHeight", hoverSealShowHeight + "px");
        }
      }),
      100
    );
  }
};

const onReset = () => {
  $(".gap-drag-area").remove();
  statusSealAdd = EnumStatusAddSeal.none;
  setBoxTemporarySeal(null);
};

//Y轴拖拽事件
const dragEventOnYAxis = (dragArea, boxConfirmSeal) => {
  console.log(" dragEventOnYAxis ...");
  let defaultTop = ($(dragArea).height() - hoverSealShowHeight) / 2;
  seal.move(boxConfirmSeal, {
    left: 0,
    top: defaultTop,
  });
  //拖拽事件
  _.assign(provideHome.movePosition, {
    left: 0,
    top: defaultTop,
  });
  let position = provideHome.movePosition;

  interact(boxConfirmSeal).draggable({
    /** 只能Y轴移动 */
    lockAxis: "y",
    modifiers: [
      interact.modifiers.restrict({
        restriction: dragArea,
        elementRect: { left: 0, right: 0, top: 0, bottom: 1 },
      }),
    ],
    listeners: {
      start(event) {
        // console.log(event.type, event.target);
      },
      move(event) {
        let yMin = 0;
        let yMax = $(".gap-drag-area").height() - hoverSealShowHeight;
        position.left = 0;
        position.top += event.dy;

        position.top = format.valueInRange(yMin, yMax, position.top);
        // console.log("move ", position);
        seal.move(event.target, {
          left: position.left,
          top: position.top,
        });
      },
    },
  });
};
//X轴拖拽事件
const dragEventOnXAxis = (dragArea, boxConfirmSeal) => {
  console.log(" dragEventOnXAxis ...");
  let defaultLeft = ($(dragArea).width() - hoverSealShowWidth) / 2;
  seal.move(boxConfirmSeal, {
    left: defaultLeft,
    top: 0,
  });
  //拖拽事件
  _.assign(provideHome.movePosition, {
    left: defaultLeft,
    top: 0,
  });
  let position = provideHome.movePosition;

  interact(boxConfirmSeal).draggable({
    /** 只能Y轴移动 */
    lockAxis: "x",
    modifiers: [
      interact.modifiers.restrict({
        restriction: dragArea,
        elementRect: { left: 0, right: 0, top: 0, bottom: 1 },
      }),
    ],
    listeners: {
      start(event) {
        // console.log(event.type, event.target);
      },
      move(event) {
        let xMin = 0;
        let xMax = $(".gap-drag-area").width() - hoverSealShowWidth;
        position.top = 0;
        position.left += event.dx;

        position.left = format.valueInRange(xMin, xMax, position.left);
        seal.move(event.target, {
          left: position.left,
          top: position.top,
        });
      },
    },
  });
};

const setDragAreaStyle = (dragArea, boxConfirmSeal, rotation = 0) => {
  if (rotation == 0) {
    dragArea.classList.add("at-right");
  } else if (rotation == 90) {
    dragArea.classList.add("at-bottom");
  } else if (rotation == 180) {
    dragArea.classList.add("at-left");
  } else if (rotation == 270) {
    dragArea.classList.add("at-top");
  }
  boxConfirmSeal.dataset.showerRotation = rotation;
  boxConfirmSeal.classList.add("box-rotation");
};

const initDragArea = () => {
  statusSealAdd = EnumStatusAddSeal.confirm;
  bindSealAddEvents();
  let pageNumber = PDFViewerApplication.toolbar.pageNumber;
  let $curPage = $(`.page:eq(${pageNumber - 1})`);

  //当前页面滑至滚动区
  $curPage[0].scrollIntoView({
    behavior: "smooth",
  });
  let rotation = +$(".textLayer", $curPage)[0].dataset.mainRotation;

  setTimeout(() => {
    $("#viewerContainer").scrollLeft(1000);
  }, 500);

  //创建垂直拖拽区域
  var dragArea = document.createElement("div");
  dragArea.className =
    "gap-drag-area drag-area box-unfinish animate__bounceInRight ";

  dragArea.dataset.sealType = "gap";
  var divVertical = document.createElement("div");
  divVertical.className = "desc";
  divVertical.textContent = "骑缝章";
  dragArea.appendChild(divVertical);
  $curPage.append(dragArea);

  dragArea.dataset.pageNumber = pageNumber;

  setSealSizeByScale();
  dragArea.style.setProperty("--sealWidth", hoverSealShowWidth + "px");
  dragArea.style.setProperty("--sealHeight", hoverSealShowHeight + "px");
  //垂直拖拽区域添加印章
  let boxConfirmSeal = seal.createConfirmSeal({
    imgSrc: format.base64ToImageSrc(state.sealInfo.sealImageBase64),
    sealType: "gap",
  });
  setDragAreaStyle(dragArea, boxConfirmSeal, rotation);
  let defaultTop = ($(dragArea).height() - hoverSealShowHeight) / 2;
  // console.log("defaultTop", defaultTop);
  $(boxConfirmSeal).appendTo(dragArea);
  seal.move(boxConfirmSeal, {
    left: 0,
    top: defaultTop,
  });

  //取消按钮点击事件
  $(".btn-cancel", boxConfirmSeal).on("click", function (event) {
    provideHome.methods.setSealCurrentOperateName("");
    seal.exitAppLinkWhenSealAdd();
    onReset();
  });

  //确定按钮点击事件
  $(".btn-submit", boxConfirmSeal).on("click", async function (event) {
    let { sealInfo } = state;
    let posInfo = seal.getRealPosition(boxConfirmSeal);

    await seal.doSealAdd({
      fileId: ss.get("fileId"),
      signatureInfo: {
        signatureType: "pageSeal",
        page: 0,
        x: 0,
        y: posInfo.top,
      },
      sealSn: sealInfo.sealSn,
      positionType: 1,
      signContinued: "00",
      sealType: sealInfo.sealType,
    });
  });

  setBoxTemporarySeal(dragArea);
  if ([90, 270].includes(rotation)) {
    dragEventOnXAxis(dragArea, boxConfirmSeal);
  } else {
    dragEventOnYAxis(dragArea, boxConfirmSeal);
  }
};

defineExpose({
  show() {
    changeCurStep(1);

    // changeCurStep(2);
  },
});
</script>
<style lang="scss">
.gap-drag-area {
  color: #2563eb;
  transition: transform 0.3s linear;
  outline: dashed 1px #276ef9;

  &.at-right {
    @apply absolute w-[var(--sealWidth)] h-full top-0 left-[100%];
  }
  &.at-left {
    @apply absolute w-[var(--sealWidth)] h-full top-0;
    left: calc(0px - var(--sealWidth));
  }
  &.at-bottom {
    @apply absolute h-[var(--sealHeight)] w-full bottom-0 left-0;
  }
  &.at-top {
    @apply absolute w-full h-[var(--sealHeight)] top-0 left-0;
  }

  background: #eff6ff
    repeating-linear-gradient(
      90deg,
      transparent,
      transparent 17%,
      rgba(0, 0, 0, 0.08) 20%
    );

  &.at-top,
  &.at-bottom {
    background: #eff6ff
      repeating-linear-gradient(
        0deg,
        transparent,
        transparent 17%,
        rgba(0, 0, 0, 0.08) 20%
      );
    .desc {
      writing-mode: horizontal-tb;
      padding-top: 0;
      padding-left: 10%;
    }
  }
  .desc {
    @apply h-full w-full v-center absolute pointer-events-none;
    writing-mode: tb;
    letter-spacing: 60px;
    padding-top: 40px;
    font-size: calc(21px * var(--scale-factor));
  }

  &:hover {
    &.at-top,
    &.at-bottom {
      background: #eff6ff90;
    }
  }
}
</style>
